package com.lanvideo.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义错误控制器
 */
@Controller
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    @RequestMapping("/error")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request) {
        Map<String, Object> errorInfo = new HashMap<>();
        
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        Object message = request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
        Object requestUri = request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
        
        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());
            errorInfo.put("status", statusCode);
            errorInfo.put("error", HttpStatus.valueOf(statusCode).getReasonPhrase());
        }
        
        errorInfo.put("message", message != null ? message.toString() : "未知错误");
        errorInfo.put("path", requestUri != null ? requestUri.toString() : "未知路径");
        errorInfo.put("timestamp", System.currentTimeMillis());
        
        // 如果是404错误，提供更详细的信息
        if (status != null && Integer.parseInt(status.toString()) == 404) {
            errorInfo.put("suggestion", "请检查URL路径是否正确");
        }
        
        return ResponseEntity.status(status != null ? Integer.parseInt(status.toString()) : 500)
                .body(errorInfo);
    }
}
